// pages/city/city.js
const app = getApp();

Page({
  data: {
    result:"",
    lists:"",
    keyword:"",
    searchCity:"",
    visitiedCities:[],
    location:""
  },
  onLoad: function (options) {
    // 定位的城市
    var location = wx.getStorageSync('locationCity')
    if(location){
      this.setData({
        location
      })
    }
    // 缓存的城市
    var cities = wx.getStorageSync('cities')
    if(cities){
      this.setData({
        visitiedCities:cities
      })
    }else{
      wx.setStorageSync('cities', [])
    }
    wx.request({
      url: 'http://192.168.4.18:8000/city',
      data: {},
      method: 'GET', 
      success:(res)=>{
        var result = res.data.data
        var lists = Object.keys(result.cities)
        this.setData({
          result,
          lists
        })
      }
    })
    
  },
  handleClick(event){
    var cities = wx.getStorageSync('cities')
    var {name} = event.currentTarget.dataset
    if(!cities.includes(name)){
      cities.unshift(name)
    }
    wx.setStorageSync('cities', cities.slice(0,3))
    app.globalData.currentCity = name
    wx.navigateBack()
  },
  onChange(event){
    var value = event.detail.trim()
    var searchCity = this.filterCity(value)
     this.setData({
       keyword:value,
       searchCity
     })
  },
  filterCity(keyword){
    var cities = this.data.result.cities
    var res = []
     for(let key in cities){
          cities[key].forEach(item=>{
          if(item.name.includes(keyword) || item.spell.includes(keyword)){
             res.push(item)
          }
        }) 
     }
     return res
  }
})